package com.example.pma.controllers;

import com.example.pma.dao.CompanyRepository;
import com.example.pma.dao.PositionRepository;
import com.example.pma.entities.Company;
import com.example.pma.entities.Position;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("positions")
public class PositionController {

    @Autowired
    PositionRepository positionRepository;

    @Autowired
    CompanyRepository companyRepository;

    @GetMapping
    public String displayPositions(Model model){

        List<Position> positions = positionRepository.findAll();
        model.addAttribute("positions",positions);
        return "positions/list-positions";
    }

    @GetMapping("/new")
    public String displayPositionForm(Model model){

        Position aPosition = new Position();
        List<Company> companies = companyRepository.findAll();
        model.addAttribute("position",aPosition);
        model.addAttribute("allCompanies",companies);
        return "positions/new-position";
    }

    @PostMapping("/save")
    public String createPosition(Model model, @RequestParam List<Long> companies,Position position){
        positionRepository.save(position);
//        Iterable<Company> chosenCompanies = companyRepository.findAllById(companies);
//
//        for(Company company : chosenCompanies){
//            company.setPosition(position);
//            companyRepository.save(company);
//        }
        return "redirect:/positions";
    }

}
